package com.example.ccj.b.c.custom.tree.tree2;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.ccj.R;
import com.example.ccj.b.c.custom.MEditTextView;
import com.example.ccj.b.c.custom.search.ISearchListener;
import com.example.ccj.b.c.custom.search.SearchView;
import com.example.ccj.b.c.custom.tree.TreeMode;
import com.example.ccj.b.c.recycler.BaseRecycler;

import com.example.ccj.u.StringUtils;
import com.example.ccj.u.ToastUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class TreeStructure2 extends LinearLayout  implements ITreeResultListener{

    String mainText = "山东省驰珺网络科技有限公司";

    private boolean onlyShowMuLu = false;   //是否至显示目录
    private boolean isCnSelectBuMen = true; //部门是否可选
    private boolean isShowSuoShuJieDian = false;    //是否显示该节点所属节点
    private boolean isCanSelectRenYuan = true;    //是否可选择人员

    List<TreeMode> selectedData;   //选中的数据
    List<TreeMode> searchList;     //搜索用数据
    Map<String,TreeMode> jumpMap;  //部门跳转用
    List<TreeMode> clickList;      //跳转的部门列表
    BaseRecycler<TreeMode> baseRecycler;  //数据展示用
    List<TreeMode> treeModes; // 所有数据

    private int selectMaxNum = 2;
    TextView mTextView;
    SearchView searchView;
    LinearLayout selectedL;


    public TreeStructure2(Context context) {
        super(context);
        init();
    }
    public TreeStructure2(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void show(){
        mTextView.setText(mainText);
    }

    /**
     * 初始化
     */
    private void init(){
        LinearLayout.inflate(getContext(), R.layout.view_tree_structure,this);
        mTextView = findViewById(R.id.view_tree_structure_title_text);
        baseRecycler = findViewById(R.id.view_tree_structure_rec);
        searchView = findViewById(R.id.view_tree_structure_search);
        selectedL = findViewById(R.id.view_tree_structure_llll1);
        selectText = findViewById(R.id.view_tree_structure_select_name);

        baseRecycler.setItemDecoration();

        jumpMap = new HashMap<>();
        selectedData = new ArrayList<>();
        clickList = new ArrayList<>();
        treeModes = new ArrayList<>();
        searchList = new ArrayList<>();
        mTextView.setText(mainText);

        //搜索事件
        searchView.show(new ISearchListener() {
            //文本改变时
            @Override
            public void textChange(CharSequence text) {
                search(text);
            }

            //获取焦点时
            @Override
            public void onFocusChange(boolean hasFocus, MEditTextView mEditTextView) {
                if (hasFocus) {
                    if (mEditTextView.getText() != null) search(mEditTextView.getText());
                }
            }

            //点击搜索按钮时
            @Override
            public void buttonClick(CharSequence text) {
                search(text);
            }
        });

        //显示选择的节点数量
        selectedL.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectedData.isEmpty()) {
                    ToastUtils.showShort("未选择");
                } else {
                    ShowSelectedTreeDialog dialog = new ShowSelectedTreeDialog(v.getContext(), selectedData,true, new ISelectedTreeDataResult() {
                        @Override
                        public void onResult() {
                            baseRecycler.getAdapter().notifyDataSetChanged();
                            setSelectedText();
                        }
                    });
                    dialog.show();
                }
            }
        });
    }

    private void search(CharSequence text){
        if (StringUtils.isEmpty(text)) {
            clickList.clear();
            handleNextText();
            setBaseRecyclerData(treeModes);
        } else {
            if (!clickList.isEmpty()) {
                clickList.clear();
                handleNextText();
            }
            List<TreeMode> searchTree = new ArrayList<>();
            for (TreeMode treeMode : searchList) {
                if (treeMode.name.contains(text)) {
                    searchTree.add(treeMode);
                }
            }
            setBaseRecyclerData(searchTree,isCnSelectBuMen,true);
        }
    }

    /**
     * 设置数据
     * @param treeModeList 树装结构数据
     */
    public void setData(List<TreeMode> treeModeList){
        setData(treeModeList,null);
    }

    /**
     * 设置数据
     * @param treeModeList 树装结构数据
     * @param selectedList 已选中的数据编号
     */
    public void setData(List<TreeMode> treeModeList,List<String> selectedList){
        searchList.addAll(treeModeList);
        treeModes = handleData(treeModeList,selectedList);
        setBaseRecyclerData(treeModes);
    }

    /**
     * 将数据放入rec显示
     * @param treeModeList 需要显示的数据
     */
    private void setBaseRecyclerData(List<TreeMode> treeModeList){
        setBaseRecyclerData(treeModeList,isCnSelectBuMen,isShowSuoShuJieDian);
    }

    /**
     * 将数据放入rec显示
     * @param treeModeList 需要显示的数据
     */
    private void setBaseRecyclerData(List<TreeMode> treeModeList,boolean isCnSelectBuMen,boolean isShowSuoShuJieDian){
        List<TreeMode> showTree = new ArrayList<>();
        if (onlyShowMuLu) {
            for (TreeMode treeMode : treeModeList) {
                if (treeMode.type == TreeMode.DATA_TYPE_MU_LU) {
                    showTree.add(treeMode);
                }
            }
        } else {
            showTree.addAll(treeModeList);
        }
        //先对数据进行排序，再展示
        Collections.sort(showTree);
        baseRecycler.setAdapter(showTree,new TreeStructureAdapter(showTree, this,isCanSelectRenYuan,isCnSelectBuMen,isShowSuoShuJieDian,selectMaxNum));
    }

    /**
     * 下一节点跳转
     * @param treeMode 要跳转的节点
     */
    @Override
    public void onNext(TreeMode treeMode) {
        if (treeMode.treeModeList != null) {
            setBaseRecyclerData(treeMode.treeModeList);
            clickList.add(treeMode);
            handleNextText();
        } else {
            ToastUtils.showShort("该节点无下级！");
        }
    }

    /**
     * 选择后的回调
     * @param treeMode 点击的节点
     * @param isSelect 是否选中
     */
    @SuppressLint("SetTextI18n")
    @Override
    public void onSelectChange(TreeMode treeMode, boolean isSelect) {
        if (isSelect) selectedData.add(treeMode);
        else selectedData.remove(treeMode);
        setSelectedText();
    }

    private void setSelectedText(){
        int i = 0;
        int j = 0;

        for (TreeMode selectedDatum : selectedData) {
            if (selectedDatum.type == TreeMode.DATA_TYPE_MU_LU) i++;
            else j++;
        }
        String text= "";
        if (i>0) {
            text = "部门：" + i + "个  ";
        }
        if (j > 0) {
            text += "人员：" + j + "个  ";
        }
        selectText.setText(text);
    }

    TextView selectText ;

    /**
     * 节点跳转
     * @param treeMode 要跳转的节点
     */
    private void jump(TreeMode treeMode){
        //主节点跳转
        if (treeMode == null) {
            clickList.clear();
            setBaseRecyclerData(treeModes);
        //子节点跳转
        } else if (treeMode.treeModeList != null) {
            setBaseRecyclerData(treeMode.treeModeList);
            int j = 0;
            for (int i = 0; i < clickList.size(); i++) {
                TreeMode treeMode1 = clickList.get(i);
                if (treeMode1.dataId.equals(treeMode.dataId)) {
                    j=i;
                }
            }
            //删除该跳转节点之后的节点
            while (clickList.size() > j+1) {
                clickList.remove(j+1);
            }
        } else {
            ToastUtils.showShort("该节点无下级！");
        }
        //重新设置路径
        handleNextText();
    }

    String fenGeFu = " > ";

    /**
     * 处理节点点击后的路径显示及跳转
     * 存在子节点时设置主节点及主节点最后一个节点不设置为当前显示节点
     * 不存在子节点时去除主节点
     */
    private void handleNextText(){
        //当当前路径为空时只显示主路径 且去掉其跳转
        if (clickList.isEmpty()) {
            mTextView.setText(mainText);
            return;
        }

        //获取节点路径
        //主节点 + 字节点
        StringBuilder stringBuilder = new StringBuilder(mainText);
        stringBuilder.append(fenGeFu);
        Iterator<TreeMode> iterator = clickList.iterator();

        while (iterator.hasNext()) {
            TreeMode next = iterator.next();
            stringBuilder.append(next.name);
            if (iterator.hasNext()) stringBuilder.append(fenGeFu);
        }

        //设置各节点的颜色以及点击跳转
        //主节点设置
        int start = mainText.length()+fenGeFu.length();
        SpannableString spannableString = new SpannableString(stringBuilder);
        ForegroundColorSpan endTextColorSpan = new ForegroundColorSpan(Color.GRAY);     //结尾节点字体颜色
        //主节点的跳转
        ClickableSpan mainClickSpan = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                jump(null);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.GREEN);   // 设置文本颜色
                ds.setUnderlineText(false); // 设置隐藏下划线
            }
        };

        //添加中间节点跳转
        spannableString.setSpan(mainClickSpan,0,start-fenGeFu.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        Iterator<TreeMode> iterator2 = clickList.iterator();
        while (iterator2.hasNext()) {
            TreeMode next = iterator2.next();
            //有下一个代表是中间节点
            if (iterator2.hasNext()) {
                ClickableSpan zhongJianClickSpan = new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View widget) {
                        jump(next);
                    }

                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setColor(Color.BLUE);   // 设置文本颜色
                        ds.setUnderlineText(false); // 设置隐藏下划线
                    }
                };
                //添加文本点击事件
                spannableString.setSpan(zhongJianClickSpan,start,start+next.name.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                start += next.name.length() +fenGeFu.length();
            } else {
                //末尾节点只改变文本颜色
                spannableString.setSpan(endTextColorSpan,start,start+next.name.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        // 确保Linkify设置为false，否则可能会和ClickableSpan冲突
        mTextView.setLinksClickable(false);
        // 设置TextView可点击
        mTextView.setMovementMethod(LinkMovementMethod.getInstance());
        mTextView.setText(spannableString);
    }

    public List<TreeMode> handleData(List<TreeMode> treeModeList,List<String> selectedList){
        //筛选出来所有目录
        Map<String,TreeMode> muLuModeMap = new HashMap<>();

        //遍历出来目录
        for (TreeMode treeMode : treeModeList) {
            if (treeMode.type == TreeMode.DATA_TYPE_MU_LU) {
                muLuModeMap.put(treeMode.dataId,treeMode);
            }
            if (selectedList != null && selectedList.contains(treeMode.dataId)) {
                treeMode.isChecked = true;
                selectedData.add(treeMode);
            }
        }

        setSelectedText();

        //创建一个临时目录存放未找到对应上级节点的数据
        TreeMode treeMode3 = new TreeMode("0000",null,"无所属",TreeMode.DATA_TYPE_MU_LU);
        treeMode3.treeModeList = new ArrayList<>();
        muLuModeMap.put("0000",treeMode3);

        //人员放入对应目录中
        for (TreeMode treeMode : treeModeList) {
            if (treeMode != null && treeMode.type == TreeMode.DATA_TYPE_DATA && !StringUtils.isEmpty(treeMode.pMuLu)) {
                TreeMode treeMode1 = muLuModeMap.get(treeMode.pMuLu);
                if (treeMode1 != null) {
                    if (treeMode1.treeModeList == null) treeMode1.treeModeList = new ArrayList<>();
                    treeMode1.treeModeList.add(treeMode);
                } else {
                    TreeMode treeMode2 = muLuModeMap.get("0000");
                    if (treeMode2 != null) treeMode2.treeModeList.add(treeMode);
                }
            }
        }

        //存在上下级关系的目录节点合并
        List<String> tagList = new ArrayList<>();
        for (String s : muLuModeMap.keySet()) {
            TreeMode treeMode = muLuModeMap.get(s);
            //当前的目录节点存在上级节点
            if (treeMode != null && !StringUtils.isEmpty(treeMode.pMuLu)) {
                //并且目录map里包含这个存在的上级节点
                if (muLuModeMap.containsKey(treeMode.pMuLu)) {
                    //获取他的上级节点
                    TreeMode treeMode1 = muLuModeMap.get(treeMode.pMuLu);
                    //上级节点存在不为空
                    if (treeMode1 != null) {
                        if (treeMode1.treeModeList == null) {
                            treeMode1.treeModeList = new ArrayList<>();
                            treeMode1.treeModeList.add(treeMode);
                        }  else {
                            //将目录插入到最前面
                            treeMode1.treeModeList.add(0,treeMode);
                        }
                        tagList.add(treeMode.dataId);
                    }
                }
            }
        }

        //如果临时目录没有数据清除掉
        if (muLuModeMap.get("0000").treeModeList.isEmpty()) muLuModeMap.remove("0000");
        jumpMap.putAll(muLuModeMap);

        // 设置人员所属节点名称
        for (TreeMode treeMode : treeModeList) {
            treeMode.buMenStr = setBuMen(treeMode, jumpMap);
        }

        for (String s : tagList) {
            muLuModeMap.remove(s);
        }
        return new ArrayList<>(muLuModeMap.values());
    }

    private List<TreeMode> thisSelectedData = new ArrayList<>();


    //获取人员所属部门
    private String setBuMen(TreeMode mode,Map<String,TreeMode> muLuModeMap){
        if (!StringUtils.isEmpty(mode.pMuLu) && muLuModeMap.containsKey(mode.pMuLu)) {
            TreeMode treeMode = muLuModeMap.get(mode.pMuLu);
            if (treeMode != null) {
                return setBuMen(treeMode,muLuModeMap) + "-" + treeMode.name  ;
            } else {
                return "";
            }
        } else {
            return "";
        }
    }

    /**
     * 获取当前选中节点下的所有节点
     * @param treeMode 选中的节点
     */
    private void getSelectedAllData(TreeMode treeMode){
        if (treeMode != null) {
            thisSelectedData.add(treeMode);
            if (treeMode.type == TreeMode.DATA_TYPE_MU_LU)  {
                List<TreeMode> treeModeList = treeMode.treeModeList;
                if (!treeModeList.isEmpty()) {
                    for (TreeMode mode : treeModeList) {
                        getSelectedAllData(mode);
                    }
                }
            }
        }
    }

    public String getMainText() {
        return mainText;
    }

    public TreeStructure2 setMainText(String mainText) {
        this.mainText = mainText;
        return this;
    }

    public boolean isOnlyShowMuLu() {
        return onlyShowMuLu;
    }

    public TreeStructure2 setOnlyShowMuLu(boolean onlyShowMuLu) {
        this.onlyShowMuLu = onlyShowMuLu;
        return this;
    }

    public boolean isCnSelectBuMen() {
        return isCnSelectBuMen;
    }

    public TreeStructure2 setCnSelectBuMen(boolean cnSelectBuMen) {
        isCnSelectBuMen = cnSelectBuMen;
        return this;
    }

    public boolean isShowSuoShuJieDian() {
        return isShowSuoShuJieDian;
    }

    public TreeStructure2 setShowSuoShuJieDian(boolean showSuoShuJieDian) {
        isShowSuoShuJieDian = showSuoShuJieDian;
        return this;
    }

    public int getSelectMaxNum() {
        return selectMaxNum;
    }

    public TreeStructure2 setSelectMaxNum(int selectMaxNum) {
        this.selectMaxNum = selectMaxNum;
        return this;
    }

    public List<TreeMode> getSelectedData() {
        return selectedData;
    }

    public List<TreeMode> getSearchList() {
        return searchList;
    }

    public Map<String, TreeMode> getJumpMap() {
        return jumpMap;
    }

    public List<TreeMode> getClickList() {
        return clickList;
    }

    public BaseRecycler<TreeMode> getBaseRecycler() {
        return baseRecycler;
    }

    public List<TreeMode> getTreeModes() {
        return treeModes;
    }

    public TextView getmTextView() {
        return mTextView;
    }

    public SearchView getSearchView() {
        return searchView;
    }

    public LinearLayout getSelectedL() {
        return selectedL;
    }

    public TextView getSelectText() {
        return selectText;
    }

    public String getFenGeFu() {
        return fenGeFu;
    }

    public List<TreeMode> getThisSelectedData() {
        return thisSelectedData;
    }

    public boolean isCanSelectRenYuan() {
        return isCanSelectRenYuan;
    }

    public void setCanSelectRenYuan(boolean canSelectRenYuan) {
        isCanSelectRenYuan = canSelectRenYuan;
    }
}
